package com.xoa.controller.AI;

import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.model.AI.AISetting;
import com.xoa.model.department.Department;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.AI.AIService;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.service.work.WorkService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 手机智能审批申请
 */
@Controller
@RequestMapping("/AI")
public class AIController {

    @Autowired
    AIService aiService;

    @Autowired
    WFEFlowRunInfo wfeFlowRunInfo;

    @Autowired
    SysCodeMapper sysCodeMapper;

    @Autowired
    WorkMapper workMapper;

    @Autowired
    WFEFormTypeMapper wfeFormTypeMapper;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    UsersService usersService;

    @Autowired
    WorkService workService;

    @Autowired
    WFEFlowRunMapper wfeFlowRunMapper;

    @Autowired
    WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    WFEFlowProcess wfeFlowProcess;

    @Autowired
    WFEFlowTypeModelMapper wfeFlowTypeModelMapper;

    @Autowired
    SmsService smsService;

    /**
     * 请假
     */
    private final static int LEAVE_APPLY = 140;
    /**
     * 外出
     */
    private final static int LEAVE_OUT = 143;
    /**
     * 出差
     */
    private final static int LEAVE_EVECTION = 142;
    /**
     * 加班
     */
    private final static int LEAVE_OVERTIME = 141;


    /**
     * 保存AI设置
     *
     * @param aiSetting
     * @param request
     * @return
     */
    @RequestMapping("/saveAISetting")
    @ResponseBody
    public AjaxJson updateByPrimaryKeySelective(AISetting aiSetting, HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        aiSetting.setUid(user.getUid());
        AISetting temp = aiService.selectByPrimaryKey(user.getUid());
        int a = 0;
        if (temp != null) {
            a = aiService.updateByPrimaryKeySelective(aiSetting);
        } else {
            a = aiService.insertSelective(aiSetting);
        }
        if (a > 0) {
            ajaxJson.setFlag(true);
        } else {
            ajaxJson.setFlag(false);
        }
        return ajaxJson;

    }

    /**
     * 发起审批
     *
     * @param type      请假类型 可去除
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param message   请假信息
     * @param request
     * @return
     */
    @RequestMapping("/leaveApply")
    @ResponseBody
    public AjaxJson leaveApply(String type, String startTime, String endTime, String message,String flowType, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        AjaxJson ajaxJson = new AjaxJson();
        //获取请求参数哈希表
        Map<String, String> map = getParamMap(request);
        try {
            //根据传入参数判断对应审批流程id号
            Integer flowId = this.getFlowId(StringUtils.checkNull(map.get("flowType")) ? 0 : Integer.valueOf(map.get("flowType")));
            //创建审批流程
            ToJson<FlowFast> result = this.createWorker(flowId, user, 1, 1);
            if (result.isFlag()) {
                FlowFast flowFast = (FlowFast) result.getObject();
                Integer runId = flowFast.getFlowRun().getRunId();
                String runName = flowFast.getFlowRun().getRunName();
                Department department = departmentService.getDeptById(user.getDeptId());
                FlowRunPrcs flowRunPrcs = flowFast.getFlowRunPrcs();
                FlowProcess flowProcess = flowFast.getFlowProcesses();

                map.put("userName", user.getUserName());
                map.put("departName", department.getDeptName());
                map.put("userPrivName", user.getUserPrivName());
                //获取表单信息
                Document document = this.getFormDocument(flowId);
                //拼接表单数据sql
                String setSql = this.getSql(flowId, document, map);

                //保存数据
                boolean flag = saveData(runId, flowId, runName, user.getUserId(), setSql);
                //流程转交
                this.transferProcess(flowRunPrcs, flowProcess, user, flowId, runName, department, request);

                if (!flag) {
                    ajaxJson.setFlag(false);
                    ajaxJson.setMsg("系统异常，请联系管理员");
                } else {
                    ajaxJson.setFlag(flag);
                }
            } else {
                ajaxJson.setFlag(false);
                ajaxJson.setMsg("系统异常，请联系管理员");
            }
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }

    /**
     * 获取最近几条待审批的工作流
     *
     * @param request
     * @param page     分页
     * @param pageSize 大小
     * @param useFlag  是否开启分页
     * @return
     */
    @RequestMapping("getRecentWorkFlow")
    @ResponseBody
    public AjaxJson getRecentWorkFlow(HttpServletRequest request, @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                      @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                      @RequestParam(name = "useFlag", required = false, defaultValue = "true") Boolean useFlag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> map = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        map.put("page", pageParams);
        map.put("userId", user.getUserId());
        AjaxJson ajaxJson = new AjaxJson();
        try {
            List<FlowRun> list = wfeFlowRunMapper.getRecentWorkFlow(map);
            Map<String, String> dataLEAVE_APPLY = null;
            Map<String, String> dataLEAVE_OUT = null;
            Map<String, String> dataLEAVE_EVECTION = null;
            Map<String, String> dataLEAVE_OVERTIME = null;
            String temp = null;
            for (FlowRun flowRun : list) {
                if (LEAVE_APPLY == flowRun.getFlowId()) {
                    if (dataLEAVE_APPLY == null) {
                        dataLEAVE_APPLY = this.getFlowData(flowRun.getFlowId());
                    }
                    temp = getRecentWorkFlowString(flowRun, dataLEAVE_APPLY);
                }
                if (LEAVE_OUT == flowRun.getFlowId()) {
                    if (dataLEAVE_OUT == null) {
                        dataLEAVE_OUT = this.getFlowData(flowRun.getFlowId());
                    }
                    temp = getRecentWorkFlowString(flowRun, dataLEAVE_OUT);
                }
                if (LEAVE_EVECTION == flowRun.getFlowId()) {
                    if (dataLEAVE_EVECTION == null) {
                        dataLEAVE_EVECTION = this.getFlowData(flowRun.getFlowId());
                    }
                    temp = getRecentWorkFlowString(flowRun, dataLEAVE_EVECTION);
                }
                if (LEAVE_OVERTIME == flowRun.getFlowId()) {
                    if (dataLEAVE_OVERTIME == null) {
                        dataLEAVE_OVERTIME = this.getFlowData(flowRun.getFlowId());
                    }
                    temp = getRecentWorkFlowString(flowRun, dataLEAVE_OVERTIME);
                }

                flowRun.setPreSet(temp);
            }
            ajaxJson.setObj(list);
            ajaxJson.setTotleNum(list.size());
            ajaxJson.setMsg("OK");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }


    /**
     * 语音审批流程
     *
     * @param runId 流水号
     * @param type  类型1是true同意 0是不同意
     * @return
     */
    @RequestMapping("/approve")
    @ResponseBody
    public AjaxJson approve(Integer runId, Integer type, Integer flowId, HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        //获取当前用户
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        try {
            FlowRun flowRun = wfeFlowRunMapper.selectBuRunId(runId);
            Department department = departmentService.getDeptById(user.getDeptId());
            String sign = user.getUserName() + " " + DateFormat.getStrDate(new Date());
            //获取当前流水号所处的流程在哪
            List<FlowRunPrcs> flowRunPrcsList = wfeFlowRunPrcsMapper.findMaxFrp(runId);
            FlowRunPrcs flowRunPrcs = flowRunPrcsList.get(0);
            //查询当前设计流程
            FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, flowRunPrcs.getFlowPrcs());
            FlowTypeModel flowTypeModel = wfeFlowTypeModelMapper.queryOneObject(flowId);
            String opinion = null;
            String msg = null;
            if (type == 1) {
                opinion = "同意";
                msg = "您批准了" + flowRun.getUserName() + "的" + flowTypeModel.getFlowName();
            } else {
                opinion = "不同意";
                msg = "您拒绝了" + flowRun.getUserName() + "的" + flowTypeModel.getFlowName();
            }
            String setSql = this.getFlowDataSql(flowProcess, opinion, sign);
            String runName = flowRun.getRunName();
            boolean flag = saveData(runId, flowId, runName, user.getUserId(), setSql);
            this.transferProcess(flowRunPrcs, flowProcess, user, flowId, runName, department, request);
            this.updateSms(flowId, flowRunPrcs.getPrcsId(), flowRunPrcs.getRunId(), flowRunPrcs.getFlowPrcs(), flowRunPrcs.getUserId());
            ajaxJson.setFlag(flag);
            ajaxJson.setMsg(msg);
            ajaxJson.setObj(msg);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }

    /**
     * 获取最近需要审批流程
     *
     * @param flowRun
     * @return
     */
    public String getRecentWorkFlowString(FlowRun flowRun, Map<String, String> mapFlowData) {
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, Object> map;
        String temp = null;
        String dateDetail = null;
        String endDetail = null;
        String msg = null;
        maps.put("tableName", "flow_data_" + flowRun.getFlowId());
        maps.put("runId", flowRun.getRunId());
        map = workMapper.select(maps);
        switch (flowRun.getFlowId()) {
            case LEAVE_APPLY:
                dateDetail = map.get(mapFlowData.get("beginTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("beginTime")).toString())
                        || DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString()) == null ? map.get(mapFlowData.get("beginTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString());
                endDetail = map.get(mapFlowData.get("endTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("endTime")).toString())
                        || DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString()) == null ? map.get(mapFlowData.get("endTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString());
                msg = StringUtils.checkNull((map.get((mapFlowData.get("msg")==null ? "":mapFlowData.get("msg"))) == null ? "" : map.get((mapFlowData.get("msg")==null ? "":mapFlowData.get("msg")))).toString().trim()) ? "，原因是：未填写" : "，原因是：" + map.get(mapFlowData.get("msg"));
                temp = map.get(mapFlowData.get("person")) + dateDetail + "至" + endDetail + "请假，类型为：" + (map.get(mapFlowData.get("type"))==null?"未填写":map.get(mapFlowData.get("type")))
                        + msg + "，是否同意？";
                break;
            case LEAVE_OUT:
                dateDetail = map.get(mapFlowData.get("beginTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("beginTime")).toString()) ? "请正确填写外出开始时间" : DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString());
                endDetail = map.get(mapFlowData.get("endTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("endTime")).toString()) ? "请正确填写外出结束时间" : DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString());
                temp = map.get(mapFlowData.get("person")) + "申请" + dateDetail + "至" + endDetail + map.get(mapFlowData.get("msg")) + "，目的地为:" + map.get(mapFlowData.get("address")) + "，是否同意？";
                break;
            case LEAVE_EVECTION:
                dateDetail = map.get(mapFlowData.get("beginTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("beginTime")).toString()) ? "请正确填写出差开始时间" : (DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString()) == null ? map.get(mapFlowData.get("beginTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString()));
                endDetail = map.get(mapFlowData.get("endTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("endTime")).toString()) ? "请正确填写出差结束时间" : (DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString()) == null ? map.get(mapFlowData.get("endTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString()));
                temp = map.get(mapFlowData.get("person")) + "申请" + dateDetail + "至" + endDetail + ",出差事由为：" + map.get(mapFlowData.get("msg")) + "，目的地为:" + map.get(mapFlowData.get("address")) +",预计费用为" +(map.get(mapFlowData.get("cost"))==null ? "未填写": map.get(mapFlowData.get("cost")))+ "，是否同意？";
                break;
            case LEAVE_OVERTIME:
                dateDetail = map.get(mapFlowData.get("beginTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("beginTime")).toString()) ? "请正确填写加班开始时间" : (DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString()) == null ? map.get(mapFlowData.get("beginTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("beginTime")).toString()));
                endDetail = map.get(mapFlowData.get("endTime")) == null || StringUtils.checkNull(map.get(mapFlowData.get("endTime")).toString()) ? "请正确填写加班结束时间" : (DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString()) == null ? map.get(mapFlowData.get("endTime")).toString() : DateCompute.getDateDetail(map.get(mapFlowData.get("endTime")).toString()));
                temp = map.get(mapFlowData.get("person")) + "申请" + dateDetail + "至" + endDetail + "加班,加班事由为" + map.get(mapFlowData.get("msg")) +  "，是否同意？";
                break;
            default:
                break;
        }
        return temp;
    }


    /**
     * 获取表单信息文本对象
     *
     * @param flowId 流程表Id号
     * @return
     */
    public Document getFormDocument(Integer flowId) {
        List<FlowFormType> forms = wfeFormTypeMapper.getFrombyFlowId(flowId);
        FlowFormType formType = forms.get(0);
        //获取表单信息
        Document document = HtmlUtil.getDom(formType.getPrintModel());
        return document;
    }


    /**
     * 目前表单样式外出登记和请假申请可以兼容，所以使用默认
     *
     * @param flowProcess
     * @param opinion
     * @param sign
     * @return
     */
    public String getFlowDataSql(FlowProcess flowProcess, String opinion, String sign) {
        switch (flowProcess.getFlowId()) {
            default:
                String prcsName = flowProcess.getPrcsName();
                //获取表单信息
                Document domApply = this.getFormDocument(flowProcess.getFlowId());
                //审批内容
                String approve = HtmlUtil.getDocumentName(domApply, prcsName);
                //审批意见
                String approOpinion = HtmlUtil.getDocumentName(domApply, prcsName + "意见");
                //审批签字
                String approSign = HtmlUtil.getDocumentName(domApply, prcsName + "签字");
                String setSql = approve + " = " + "'" + opinion + "'" + ","
                        + approOpinion + " = " + "'" + opinion + "'" + ","
                        + approSign + " = " + "'" + sign + "'";
                return setSql;
        }
    }


    /**
     * @param runId
     * @param flowId
     * @param runName
     * @param userId
     * @param setSql
     * @return
     */
    public boolean saveData(Integer runId, Integer flowId, String runName, String userId, String setSql) {
        //boolean flag = false;
        Map<String, Object> maps = new HashMap<String, Object>();
        String sqlType = ContextHolder.getConsumerType();
        String tableName = "flow_data_" + flowId;
        maps.put("tableName", tableName);
        maps.put("runId", runId);
        maps.put("tableSchema", sqlType);
        Map<String, Object> map = this.getFlowData(tableName, sqlType, runId, flowId);
        //用于存储数据库插入的字段
        List<String> key = new ArrayList<String>();
        List<Object> value = new ArrayList<Object>();
        try {
            if (map == null || map.size() == 0) {
                key.add("RUN_ID");
                value.add(String.valueOf(runId));
                key.add("RUN_NAME");
                value.add(runName);
                key.add("BEGIN_TIME");
                value.add(DateFormat.getStrDate(new Date()));
                key.add("BEGIN_USER");
                value.add(userId);
                //获取该表所有的列
                List<String> columns = workMapper.showColumns(maps);
                for (String s : columns) {
                    if (s.contains("DATA_")) {
                        key.add(s);
                        value.add("");
                    }
                }

                maps.put("tableName", tableName);
                maps.put("keys", key);
                maps.put("values", value);
                workMapper.insert(maps);
            }
            int a = workMapper.updateDataValue(setSql, tableName, runId);
            if (a > 0) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            e.getMessage();
        }
        return false;
    }

    /**
     * 流程转交
     *
     * @param flowRunPrcs
     * @param flowProcess
     * @param user
     * @param flowId
     * @param runName
     * @param department
     * @param request
     */
    public void transferProcess(FlowRunPrcs flowRunPrcs, FlowProcess flowProcess, Users user, Integer flowId, String runName, Department department, HttpServletRequest request) {
        //获取流程分支
        Integer runId = flowRunPrcs.getRunId();
        AjaxJson ajaxJson1 = wfeFlowRunInfo.getBranch(flowId, flowRunPrcs.getFlowPrcs(), runId, user);

        List<Users> usersList = null;
        //定义下一步骤设计流程步骤号
        Integer flowPrcs = null;
        //可选人员
        String[] prcsTo = flowProcess.getPrcsTo().split(",");

        if (StringUtils.checkNull(prcsTo[0])) {
            flowPrcs = flowProcess.getPrcsId() + 1;
        } else {
            flowPrcs = Integer.parseInt(prcsTo[0]);
        }
        Map<Integer, Map<String, Object>> m = (Map) ajaxJson1.getObj();
        for (Map.Entry<Integer, Map<String, Object>> entry : m.entrySet()) {
            //获取自动选人
            usersList = (List<Users>) entry.getValue().get("autoTypelist");
            break;
        }
        String beginUser = null;
        String jingbanUser = null;
        if (usersList!=null && usersList.size()>0){
            for (Users u : usersList){
                if ("1".equals(u.getOpFlag())){
                    beginUser = u.getUserId();
                }
                jingbanUser =StringUtils.checkNull(jingbanUser)?u.getUserId():jingbanUser+","+ u.getUserId();
            }
        }

        if (usersList == null || usersList.size() == 0) {
            PageParams pageParams = new PageParams();
            pageParams.setPage(1);
            pageParams.setPageSize(1);
            pageParams.setUseFlag(true);

            AjaxJson ajaxJson2 = wfeFlowRunInfo.getWorkFlowUser(flowId, flowPrcs, user, null, null, null, null, pageParams);
            usersList = (List<Users>) ajaxJson2.getObj();
            if (usersList == null || usersList.size() == 0) {
                if (department != null) {
                    if (!StringUtils.checkNull(department.getManager())) {
                        usersList = usersService.getUserByuserId(department.getManager());
                    }
                }
            }
        }
        if (StringUtils.checkNull(beginUser)){
            if (usersList == null || usersList.size() == 0){
                beginUser = user.getUserId();
            }else{
                beginUser = usersList.get(0).getUserId();
            }
        }
        if (StringUtils.checkNull(jingbanUser)){
            jingbanUser = beginUser;
        }

        String smsContet = "流水号：" + runId + "，工作名称/文号：" + runName;
        String prcsId = flowRunPrcs.getPrcsId().toString();
        String currentPrcsId = flowRunPrcs.getFlowPrcs().toString();
        wfeFlowRunInfo.savework(runId, runName, Integer.parseInt(prcsId), flowPrcs.toString(),DateFormat.getStrDate(new Date()),
                beginUser, jingbanUser, "", user, Integer.parseInt(currentPrcsId), "0", "", "",smsContet,"1","");
        //workService.todoWorkSmsBoby(beginUser, flowPrcs.toString(), "", runId.toString(), runName, String.valueOf(flowId), prcsId, currentPrcsId, "", null, smsContet, request, "1,", usersList.get(0), "", beginUser, "");
    }


    /**
     * 流程审批的流程类型默认请假
     *
     * @param flowType
     * @return
     */
    public Integer getFlowId(Integer flowType) {
        switch (flowType) {
            //外出
            case 1:
                return LEAVE_OUT;
            //出差
            case 2:
                return LEAVE_EVECTION;
            //加班
            case 3:
                return LEAVE_OVERTIME;
            //请假
            default:
                return LEAVE_APPLY;
        }
    }

    /**
     * 流程审批发起工作流
     *
     * @param flowId
     * @param user
     * @return
     */
    public ToJson<FlowFast> createWorker(Integer flowId, Users user, Integer prcsId, Integer flowPrcs) {
        ToJson<FlowFast> result = wfeFlowRunInfo.workFastAdd(user, flowId, prcsId, flowPrcs + "", "", null, null, "", null);
        return result;
    }

    /**
     * 获取拼接sql
     *
     * @param flowId   流程编号
     * @param document 文本对象
     * @param map      映射参数
     * @return
     */
    public String getSql(Integer flowId, Document document, Map<String, String> map) {
        String setSql = null;
        switch (flowId) {
            case LEAVE_APPLY:
                setSql = HtmlUtil.getDocumentName(document, "申请人") + " = " + "'" + map.get("userName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请部门") + " = " + "'" + map.get("departName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请时间") + " = " + "'" + DateFormat.getStrDate(new Date()) + "'" + ","
                        + HtmlUtil.getDocumentName(document, "请假类型") + " = " + "'" + map.get("type") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "请假开始时间") + " = " + "'" + map.get("startTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "请假结束时间") + " = " + "'" + map.get("endTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "请假事由") + " = " + "'" + map.get("message") + "'" + " ";
                return setSql;
            case LEAVE_OUT:
                setSql = HtmlUtil.getDocumentName(document, "申请人") + " = " + "'" + map.get("userName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请部门") + " = " + "'" + map.get("departName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请时间") + " = " + "'" + DateFormat.getStrDate(new Date()) + "'" + ","
                        + HtmlUtil.getDocumentName(document, "职务") + " = " + "'" + map.get("userPrivName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "外出开始时间") + " = " + "'" + map.get("startTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "外出结束时间") + " = " + "'" + map.get("endTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "外出单位") + " = " + "'" + map.get("unit") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "外出地点") + " = " + "'" + map.get("address") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "外出事由") + " = " + "'" + map.get("message") + "'" + " ";
                return setSql;
            case LEAVE_EVECTION:
                setSql = HtmlUtil.getDocumentName(document, "申请人") + " = " + "'" + map.get("userName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请部门") + " = " + "'" + map.get("departName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请时间") + " = " + "'" + DateFormat.getStrDate(new Date()) + "'" + ","
                        + HtmlUtil.getDocumentName(document, "职务") + " = " + "'" + map.get("userPrivName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "出差开始时间") + " = " + "'" + map.get("startTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "出差结束时间") + " = " + "'" + map.get("endTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "预计费用") + " = " + "'" + map.get("cost") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "出差地点") + " = " + "'" + map.get("address") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "出差事由") + " = " + "'" + map.get("message") + "'" + " ";
                return setSql;
            case LEAVE_OVERTIME:
                setSql = HtmlUtil.getDocumentName(document, "申请人") + " = " + "'" + map.get("userName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请部门") + " = " + "'" + map.get("departName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "申请时间") + " = " + "'" + DateFormat.getStrDate(new Date()) + "'" + ","
                        + HtmlUtil.getDocumentName(document, "职务") + " = " + "'" + map.get("userPrivName") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "加班开始时间") + " = " + "'" + map.get("startTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "加班结束时间") + " = " + "'" + map.get("endTime") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "加班地点") + " = " + "'" + map.get("address") + "'" + ","
                        + HtmlUtil.getDocumentName(document, "加班事由") + " = " + "'" + map.get("message") + "'" + " ";
                return setSql;
            default:
                return null;
        }
    }

    /**
     * 获取表单上对应data
     *
     * @param flowId
     * @return
     */
    public Map<String, String> getFlowData(Integer flowId) {
        //获取表单信息
        Document document = this.getFormDocument(flowId);
        Map<String, String> map = new HashMap<String, String>();
        switch (flowId) {
            case LEAVE_APPLY: //请假140
                map.put("person", HtmlUtil.getDocumentName(document, "申请人"));
                map.put("beginTime", (HtmlUtil.getDocumentName(document, "请假开始时间")==null ? HtmlUtil.getDocumentName(document, "开始时间"): HtmlUtil.getDocumentName(document, "请假开始时间")));
                map.put("endTime", (HtmlUtil.getDocumentName(document, "请假结束时间")==null ? HtmlUtil.getDocumentName(document, "结束时间"): HtmlUtil.getDocumentName(document, "请假结束时间")));
                map.put("type", HtmlUtil.getDocumentName(document, "请假类型"));
                map.put("msg", (HtmlUtil.getDocumentName(document, "请假事由")==null ? HtmlUtil.getDocumentName(document, "请假原因"):HtmlUtil.getDocumentName(document, "请假事由")));
                return map;
            case LEAVE_OUT: //外出143
                map.put("person", HtmlUtil.getDocumentName(document, "申请人"));
                map.put("address", (HtmlUtil.getDocumentName(document, "外出单位") ==null ? HtmlUtil.getDocumentName(document, "地点"):HtmlUtil.getDocumentName(document, "外出单位")));
                map.put("beginTime", (HtmlUtil.getDocumentName(document, "外出开始时间")==null ? HtmlUtil.getDocumentName(document, "开始时间"): HtmlUtil.getDocumentName(document, "外出开始时间")));
                map.put("endTime", (HtmlUtil.getDocumentName(document, "外出结束时间")==null ? HtmlUtil.getDocumentName(document, "结束时间"): HtmlUtil.getDocumentName(document, "外出结束时间" )));
                map.put("msg", (HtmlUtil.getDocumentName(document, "外出事由")==null ? HtmlUtil.getDocumentName(document, "外出原因"):HtmlUtil.getDocumentName(document, "外出事由")));
                return map;
            case LEAVE_EVECTION: //出差142
                map.put("person", HtmlUtil.getDocumentName(document, "申请人"));
                map.put("address", (HtmlUtil.getDocumentName(document, "出差地点")==null ? HtmlUtil.getDocumentName(document, "出差地址"):HtmlUtil.getDocumentName(document, "出差地点")));
                map.put("beginTime", (HtmlUtil.getDocumentName(document, "出差开始时间") ==null ? HtmlUtil.getDocumentName(document, "开始时间"):HtmlUtil.getDocumentName(document, "出差开始时间")));
                map.put("endTime", (HtmlUtil.getDocumentName(document, "出差结束时间") ==null ? HtmlUtil.getDocumentName(document, "结束时间"):HtmlUtil.getDocumentName(document, "出差结束时间")));
                map.put("msg", (HtmlUtil.getDocumentName(document, "出差事由")==null ? HtmlUtil.getDocumentName(document, "出差原因"):HtmlUtil.getDocumentName(document, "出差事由")));
                map.put("cost", HtmlUtil.getDocumentName(document, "预计费用"));
                return map;
            case LEAVE_OVERTIME: //加班141
                map.put("person", HtmlUtil.getDocumentName(document, "申请人"));
                map.put("address", (HtmlUtil.getDocumentName(document, "加班地点")==null ? HtmlUtil.getDocumentName(document, "地址定位"):HtmlUtil.getDocumentName(document, "加班地点")));
                map.put("beginTime", (HtmlUtil.getDocumentName(document, "加班开始时间")==null ? HtmlUtil.getDocumentName(document, "开始时间"):HtmlUtil.getDocumentName(document, "加班开始时间")));
                map.put("endTime", (HtmlUtil.getDocumentName(document, "加班结束时间")==null ? HtmlUtil.getDocumentName(document, "结束时间"):HtmlUtil.getDocumentName(document, "加班结束时间")));
                map.put("msg", (HtmlUtil.getDocumentName(document, "加班事由") ==null ? HtmlUtil.getDocumentName(document, "加班内容"):HtmlUtil.getDocumentName(document, "加班事由")));
                return map;
            default:
                return null;
        }
    }


    /**
     * 取得参数哈希表
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParamMap(HttpServletRequest request) {
        Map<String, String> rtMap = new HashMap<String, String>();
        Map<String, String[]> paramMap = request.getParameterMap();

        Iterator<String> iKeys = paramMap.keySet().iterator();
        while (iKeys.hasNext()) {
            String key = iKeys.next();
            String[] value = paramMap.get(key);
            if (value != null && value.length > 0) {
                rtMap.put(key, value[0]);
            } else {
                rtMap.put(key, "");
            }
        }

        return rtMap;
    }


    //查询表单对应数据
    public Map<String, Object> getFlowData(String tableName, String sqlType, Integer runId, Integer flowId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", tableName);
        if (StringUtils.checkNull(sqlType)) {
            param.put("tableSchema", "xoa1001");
        } else {
            param.put("tableSchema", sqlType);
        }
        //获取该表所有的列
        try {
            //获取表对应所有列 验证是否存在此表
            List<String> columns = workMapper.showColumns(param);
            //没有表则新建
            if (columns.size() == 0) {
                //获取表单信息
                Document document = this.getFormDocument(flowId);
                //返回表单对应所有字段，data_xx
                List<String> key = HtmlUtil.getAllData(document);
                param.put("tableName", tableName);
                param.put("keys", key);
                //读取配置文件
                ResourceBundle rb = ResourceBundle.getBundle("jdbc-sql");
                String databaseId = rb.getString("driverClassName");
                if (databaseId.contains("oracle")) {
                    workMapper.createSequence(param);
                }
                workMapper.createTable(param);
            }
            param.put("runId", runId);
            Map<String, Object> map = workMapper.select(param);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public void updateSms(Integer flowId, Integer prcsId, Integer runId, Integer currentPrcsId, String userId) {
        String smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + prcsId + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        smsService.updatequerySmsByType("7", userId, smsUrl.trim());
    }


}
